package org.kepler.chat.api.infra.security.auth;

import org.apache.commons.codec.digest.DigestUtils;
import org.kepler.chat.api.entity.AuthUser;
import org.kepler.chat.api.infra.constant.Constants;
import org.kepler.chat.api.infra.security.exceptions.JwtBadCredentialsException;
import org.kepler.chat.api.infra.security.model.UserContext;
import org.kepler.chat.api.infra.util.ErrorCode;
import org.kepler.loan.api.service.CustomUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @author ake
 * <p>
 * Aug 3, 2016
 */
@Component
public class RestAuthenticationProvider implements AuthenticationProvider {
    private final BCryptPasswordEncoder encoder;

    @Resource
    private CustomUserService customUserService;

    @Autowired
    public RestAuthenticationProvider(final BCryptPasswordEncoder encoder) {
        this.encoder = encoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.notNull(authentication, "No authentication data provided");

        UserContext userContext = null;
        String loginFlagUserName = (String) authentication.getPrincipal();
        String[] array = loginFlagUserName.split("-");
        String loginFlag = array[0];
        if (Constants.LOGINFLAG_USER.equals(loginFlag)) {
            String password = (String) authentication.getCredentials();
            AuthUser authUser = (AuthUser) customUserService.loadUserByUsername(loginFlagUserName);
            if (null == authUser) {
                throw new JwtBadCredentialsException(ErrorCode.USER_NOT_EXIST);
            }
            if (!authUser.getPassword().equals(DigestUtils.md5Hex(password))) {
                throw new JwtBadCredentialsException(ErrorCode.PARM_PASSWORD_ERROR);
            }
            //        if (user.getRoles() == null) throw new InsufficientAuthenticationException("User has no roles assigned");
            //        List<GrantedAuthority> authorities = user.getRoles().stream()
            //                .map(authority -> new SimpleGrantedAuthority(authority.getRole().authority()))
            //                .collect(Collectors.toList());
            userContext = UserContext.create(authUser.getUsername(), authUser.getAuthorities());
            userContext.setUserId(authUser.getId());
        }
        return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
